/****************************************************************************
 Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
 
 http://www.cocos2d-x.org
 
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:
 
 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 ****************************************************************************/
#include <stdlib.h>
#include <strings.h>

#include <map>
#include <string>
#include <atomic>
#include <random>                                // For random_device class

#include "HelloWorldScene.h"
#include "base/CCDirector.h"

#include "renderer/CCRenderer.h"
#include "renderer/CCCustomCommand.h"

#include "BlueToothHelper.h"
#include "RemoteControlHelper.h"
#include "network/HttpClient.h"

#include "HandWriteScene.h"
#include "HandTianScene.h"

#include "SocketIOHelper.h"
#include "ClassPathChoose.h"
#include "SIOUserInfo.h"

#define  GAME_UUID_IN_NDK "GAME_UUID_IN_NDK.plist"
#define  LOGIN_USER_INFO "LOGIN_USER_INFO.plist"


PenStatus BlueToothHelper::last_penStatus = PenStatus_NOTHING;
int BlueToothHelper::connectDeviceType = -1;
cocos2d::extension::TableView* HelloWorld::bleTabView = nullptr;
int HelloWorld::curBleCellIdx = -1;

float BlueToothHelper::last_penX=0.0;
float BlueToothHelper::last_penY=0.0;
std::string BlueToothHelper::connectBleMacId;

unsigned int HelloWorld::BLE_STATUE_STOP = 99;
unsigned int HelloWorld::BLE_STATUE_SCANING = 1;
unsigned int HelloWorld::BLE_STATUE_CONNECTING = 2;
unsigned int HelloWorld::BLE_STATUE_CONNECTED = 3;

bool HelloWorld::isDisplayDetail = false;

std::atomic<unsigned int> HelloWorld::currBleStatus(HelloWorld::BLE_STATUE_SCANING);

#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
#include "platform/android/jni/JniHelper.h"
#include "../cocos2d/cocos/platform/android/jni/JniHelper.h"
#include "../cocos2d/cocos/scripting/deprecated/CCDeprecated.h"
#include "../cocos2d/cocos/base/ccUTF8.h"
#include "../cocos2d/cocos/base/ccMacros.h"
#include "../cocos2d/cocos/base/CCDirector.h"

_oneRecvBuf oneRecvBuf;

std::map<std::string,std::string> searchBLEDeivce;

extern "C" {
JNIEXPORT void JNICALL Java_org_cocos2dx_cpp_AppActivity_ScanCallback(JNIEnv * env, jobject obj, jstring  deviceName,jstring deviceAddress,jint rssi,jint deviceVendor){
    std::string dName;
    std::string dAddress;

    NDK_CPP_Utils::jstring2String(env,deviceName, dName);
    NDK_CPP_Utils::jstring2String(env, deviceAddress, dAddress);
    LOGD("扫描到一个蓝牙咩");

    if(searchBLEDeivce.find(dAddress) == searchBLEDeivce.end()){
        searchBLEDeivce[dAddress] = dName;

        if(HelloWorld::bleTabView != nullptr){
            HelloWorld::bleTabView->reloadData();
        }
    }

    if(dName.find_first_of("XJ") == 0){
        //BlueToothHelper::ConnectByMacId(dAddress);
    }

    if(BlueToothHelper::notifyTarget != nullptr){
        BlueToothHelper::notifyTarget->setNotifyLabel("扫描到一个蓝牙"+dName);
    }

    LOGD("ScanCallback");
}

JNIEXPORT void JNICALL Java_org_cocos2dx_cpp_AppActivity_StartBluetoothScan(JNIEnv * env, jobject obj){
LOGD("StartBlueScan");

    if(BlueToothHelper::notifyTarget != nullptr){
        BlueToothHelper::notifyTarget->setNotifyLabel("开始蓝牙扫描");
    }
}

JNIEXPORT void JNICALL Java_org_cocos2dx_cpp_AppActivity_StopBluetoothScan(JNIEnv * env, jobject obj){
    LOGD("StopBluetoothScan");
    if(BlueToothHelper::notifyTarget != nullptr){
        BlueToothHelper::notifyTarget->setNotifyLabel("停止蓝牙扫描");
    }
}

JNIEXPORT void JNICALL Java_org_cocos2dx_cpp_AppActivity_NotifyCommon(JNIEnv * env, jobject obj,jstring msgJav){
    std::string msgCpp;

    NDK_CPP_Utils::jstring2String(env,msgJav, msgCpp);

    if(BlueToothHelper::notifyTarget != nullptr){
        BlueToothHelper::notifyTarget->setNotifyLabel(msgCpp);
    }
}


JNIEXPORT void JNICALL Java_org_cocos2dx_cpp_AppActivity_ScaningNotify(JNIEnv * env, jobject obj,jint step,jstring msgJava){
    LOGD("ScaningNotify");
    std::string msgCpp;
    /*
                        ScanStopNotify(1,"已连接蓝牙");
                        ScanStopNotify(-1,"已断开连接");
                        ScanStopNotify(2,"发现蓝牙服务");
                        ScanStopNotify(3,"探测服务地址"+indicate_UUID_service);
    */
    NDK_CPP_Utils::jstring2String(env,msgJava, msgCpp);

    LOGD("得到消息");
    if(BlueToothHelper::notifyTarget != nullptr){
        BlueToothHelper::notifyTarget->setNotifyLabel(msgCpp);
    }
}

JNIEXPORT void JNICALL Java_org_cocos2dx_cpp_AppActivity_HsdBLEReciveData(JNIEnv * env, jobject obj,jint penState,jfloat coordX,jfloat coordY,jfloat coordForce,jfloat strokeNum,jstring pageAddrJava)
{
    std::string pageMac;
    NDK_CPP_Utils::jstring2String(env, pageAddrJava, pageMac);

    //   static_cast<int>()
    BlueToothHelper::parseHSDRaw((int) penState,(float) coordX,(float) coordY,(float) coordForce,(float) strokeNum,pageMac);
}


JNIEXPORT void JNICALL Java_org_cocos2dx_cpp_AppActivity_BtB5ReciveData(JNIEnv * env, jobject obj,jint penState,jfloat coordX,jfloat coordY,jfloat coordForce)
{

    BlueToothHelper::parseBtB5Raw((int) penState,(float) coordX,(float) coordY,(float) coordForce);
}


JNIEXPORT void JNICALL Java_org_cocos2dx_cpp_AppActivity_BLEReciveData(JNIEnv * env, jobject obj,jbyteArray data)
{
    bzero(&oneRecvBuf,sizeof(oneRecvBuf));

    oneRecvBuf.len  = env->GetArrayLength(data);
    if(oneRecvBuf.len > 64){
         LOGD("接受到的数据包过大了。。");
        oneRecvBuf.len = 64;
    }else{
    //LOGD("接受到数据包");
    }

    std::string cnt("连接成功");
    //cnt.append(std::to_string(oneRecvBuf.len)).append("个字节");
    //BlueToothHelper::notifyTarget->setNotifyLabel(cnt);

    env->GetByteArrayRegion(data,0,oneRecvBuf.len,(jbyte*)oneRecvBuf.buf);

    BlueToothHelper::parseByRaw(oneRecvBuf);

}

JNIEXPORT void JNICALL Java_org_cocos2dx_cpp_AppActivity_BleCppInit(JNIEnv * env, jobject obj)
{
    if(BlueToothHelper::notifyTarget != nullptr){
    //static_cast<HelloWorld*>(BlueToothHelper::notifyTarget)->beginScanBLE();
    }
}


JNIEXPORT void JNICALL Java_org_cocos2dx_cpp_AppActivity_Keypress2Cpp(JNIEnv * env, jobject obj,jint keycode)
{
    BlueToothHelper::keyProc(static_cast<int>(keycode));
}

JNIEXPORT void JNICALL Java_org_cocos2dx_cpp_AppActivity_BLEConnectSuccess(JNIEnv * env, jobject obj,jint deviceType)
{
    HelloWorld::BLE_StatusChange(HelloWorld::BLE_STATUE_CONNECTED, deviceType);
    BlueToothHelper::stopScanBle();
}

JNIEXPORT void JNICALL Java_org_cocos2dx_cpp_AppActivity_BLEDisconnect(JNIEnv * env, jobject obj)
{
    HelloWorld::BLE_StatusChange(HelloWorld::BLE_STATUE_STOP, -1);
}

}
#endif

USING_NS_CC;
USING_NS_CC_EXT;

Scene* HelloWorld::createClassPathChooseScene()
{
    return ClassPathChoose::createScene();
}

Scene* HelloWorld::createScene()
{
    return HelloWorld::create();
}

void HelloWorld::setNotifyLabel(std::string cnt)
{
    if(displayLabel != nullptr) {
        if(!HelloWorld::isDisplayDetail) {
            displayLabel->setString(cnt);
        }else{
            auto newCnt = StringUtils::format("%s\n%s", connectBleLabel->getString().c_str(),cnt.c_str());

            connectBleLabel->setString(newCnt);
            Director::getInstance()->getScheduler()->performFunctionInCocosThread([&, this]{
                float disLabY = Director::getInstance()->getVisibleSize().height - connectBleLabel->getContentSize().height;
                connectBleLabel->setPosition(Vec2(20, disLabY));//visibleSize.width*0.64, 0
            });
        }
    }
}

void HelloWorld::BLE_StatusChange(unsigned int changeCode,int deviceType)
{
    HelloWorld::currBleStatus = changeCode;

    if(BlueToothHelper::notifyTarget == nullptr){
        return;
    }

    if(HelloWorld::currBleStatus == HelloWorld::BLE_STATUE_STOP){
        BlueToothHelper::notifyTarget->setNotifyLabel("断开连接");
    }

    if(HelloWorld::currBleStatus == HelloWorld::BLE_STATUE_CONNECTED){
        if(!HelloWorld::isDisplayDetail) {
            return;
        }
        if(BlueToothHelper::notifyTarget == nullptr){
            return;
        }

        BlueToothHelper::notifyTarget->setNotifyLabel("已连接成功，开始自由书写");

        HelloWorld::isDisplayDetail = false;

        auto visibleSize = Director::getInstance()->getVisibleSize();

        auto promptLayer = (LayerColor*)(static_cast<HelloWorld*>(BlueToothHelper::notifyTarget)->getChildByName("promptLayer"));
        auto moveTo = MoveTo::create(1, Vec2(visibleSize.width, 0));

        //==========================================================
        TableViewCell *oneCell = bleTabView->cellAtIndex(curBleCellIdx);
        if(oneCell == nullptr){
            return;
        }
        auto oneLab = (Label*)oneCell->getChildByName("nameAndMac");
        oneLab->setString("√");

        auto oneSprite = (Sprite*)oneCell->getChildByName("logo");
        oneSprite->stopAllActions();
        if(static_cast<HelloWorld*>(BlueToothHelper::notifyTarget)->isNeedSaveUserInfo) {
            static_cast<HelloWorld*>(BlueToothHelper::notifyTarget)->storeUserInfoToLocal(false);
        }

        // actions
        //this->stopAllActions();
        // timers
        //this->unscheduleAllCallbacks();
        checkoutGlobal();

        BlueToothHelper::connectDeviceType = deviceType;
        if(deviceType == 1 ||
           deviceType == 3
        ){
            auto scene = ClassPathChoose::createScene();
            //auto scene = HandWriteScene::createScene();
            Director::getInstance()->replaceScene(
                    TransitionFade::create(2.5, scene, Color3B(58, 81, 73)));
        }else if(deviceType == 2){
            auto scene = HandTianScene::createScene();
            Director::getInstance()->replaceScene(
                    TransitionFade::create(2.5, scene, Color3B(58, 81, 73)));
        }
    }
}
// on "init" you need to initialize your instance
bool HelloWorld::init() {
    //////////////////////////////
    // 1. super init first
    if (!Scene::init()) {
        return false;
    }


    return true;
}
void HelloWorld::initGlobal(){
    BlueToothHelper::notifyTarget = static_cast<BlueToothHelperDelegate *>(this);
    SocketIOHelper::delegate =  static_cast<SocketIOHelperDelegate *>(this);
    initKeyBoard();
    initUserInfoFromLocal();
}
void HelloWorld::onlineTest()
{
    std::string jsonRaw = "{\"roomId\":\"2194907739d-1142882900d-17369897\",\"role\":\"ND_WX\",\"avatar\":\"https://thirdwx.qlogo.cn/mmopen/vi_32/pFAYz8CDo3feCicR8ucvgQmicvbnGKVjricqjulibRL2djwCs1xInZn8Riceb5l7TQljeyNErYYnTBw0WjicVQ4Wuk6w/132\",\"nickname\":\"韩述 \",\"gender\":\"1\",\"signature\":\"o9_9fwf6KpsjcIdG2ZvheuWY3_DA\",\"lastSign\":\"\"}";

    rapidjson::Document document;
    document.Parse(jsonRaw.c_str());

    if(document.HasMember("roomId")){
        loginUserInfo.roomId = document["roomId"].GetString();
    }

    if(document.HasMember("signature")){
        loginUserInfo.signature = document["signature"].GetString();
    }

    if(document.HasMember("avatar")){
        loginUserInfo.avatar = document["avatar"].GetString();
    }
    if(document.HasMember("gender")){
        loginUserInfo.gender = document["gender"].GetString();
    }
    if(document.HasMember("role")){
        loginUserInfo.role = document["role"].GetString();
    }
    if(document.HasMember("signature")){
        loginUserInfo.signature = document["signature"].GetString();
    }
    if(document.HasMember("nickname")){
        loginUserInfo.nickname = document["nickname"].GetString();
    }
}

void HelloWorld::writeGameUUIDInfo() {
    std::random_device rd;                         // A function object for generating seeds
    std::string myRand = StringUtils::format("%ud-%ud-%ud",rd(), rd(), rd());
    if(myRand.length() > 32){
        myRand = myRand.substr(0,32);
    }

    ValueMap pageInfo;
    pageInfo["login_sign"] = Value(myRand);
    pageInfo["avatar"] = Value("");
    pageInfo["gender"] = Value("");
    pageInfo["signature"] = Value("");

    std::string writablePath = FileUtils::getInstance()->getWritablePath();
    std::string fullPath = writablePath + GAME_UUID_IN_NDK;
    if (FileUtils::getInstance()->writeValueMapToFile(pageInfo, fullPath.c_str())) {
        setNotifyLabel("初始页码存储完毕√");
        loginInInfo = pageInfo;
    } else {
        setNotifyLabel("初始页码存储失败×");
    }
}

void HelloWorld::initStoreUUIDAndRegister() {
    std::string writablePath = FileUtils::getInstance()->getWritablePath();
    writablePath.append(GAME_UUID_IN_NDK);
    FileUtils::getInstance()->isFileExist(writablePath, [=](bool isExist) {
        if (isExist) {
            loginInInfo = FileUtils::getInstance()->getValueMapFromFile(writablePath);
        } else {
            writeGameUUIDInfo();
        }

        SioJoinRoom();
    });
}

void HelloWorld::SioJoinRoom(){
    std::string channelName = loginInInfo["login_sign"].asString();
    SocketIOHelper::getInstant()->emit("store-roomid", channelName);

    channelName.append("\r\nND_LOGIN\r\navatorloginOTT\r\n智慧好字帖\r\n1\r\nsignatureloginOTT\r\n ");
    SocketIOHelper::getInstant()->emit("join-room", channelName);
};

void HelloWorld::SioConnection(SIOClient *client, const std::string&data){
    initStoreUUIDAndRegister();
    setNotifyLabel("初始页码存储完毕√");
}
void HelloWorld::SioOnline(SIOClient *client, const std::string&jsonRaw) {
    rapidjson::Document document;
    document.Parse(jsonRaw.c_str());

    bool isOk = true;
    if(document.HasMember("roomId")) {
        loginUserInfo.roomId = document["roomId"].GetString();
    }else{
        isOk = false;
    }

    if(document.HasMember("signature")){
        loginUserInfo.signature = document["signature"].GetString();
    }else{
        isOk = false;
    }

    if(document.HasMember("avatar")){
        loginUserInfo.avatar = document["avatar"].GetString();
    }else{
        isOk = false;
    }

    if(document.HasMember("gender")){
        loginUserInfo.gender = document["gender"].GetString();
    }else{
        isOk = false;
    }

    if(document.HasMember("role")){
        loginUserInfo.role = document["role"].GetString();
    }else{
        isOk = false;
    }

    if(document.HasMember("signature")){
        loginUserInfo.signature = document["signature"].GetString();
    }else{
        isOk = false;
    }

    if(document.HasMember("nickname")){
        loginUserInfo.nickname = document["nickname"].GetString();
    }else{
        isOk = false;
    }

    if(isOk){
        storeUserInfoToLocal();
    }
}

void HelloWorld::storeUserInfoToLocal(bool isLoadingUseFace){
    ValueMap userInfo;

    userInfo["roomId"] = loginUserInfo.roomId;
    userInfo["signature"] = loginUserInfo.signature ;
    userInfo["avatar"] = loginUserInfo.avatar ;
    userInfo["gender"] = loginUserInfo.gender ;
    userInfo["role"] = loginUserInfo.roomId ;
    userInfo["signature"] = loginUserInfo.signature ;
    userInfo["nickname"] = loginUserInfo.nickname ;
    userInfo["connect_macid"] = Value(BlueToothHelper::connectBleMacId);

    std::string writablePath = FileUtils::getInstance()->getWritablePath();
    std::string fullPath = writablePath + LOGIN_USER_INFO;
    if (FileUtils::getInstance()->writeValueMapToFile(userInfo, fullPath.c_str())) {
        //setNotifyLabel("初始页码存储完毕√");
        if(isLoadingUseFace) {
            downloadFriend(loginUserInfo.avatar, "登录用户头像");
        }
    } else {

    }
}

void HelloWorld::initUserInfoFromLocal() {
    std::string writablePath = FileUtils::getInstance()->getWritablePath();
    writablePath.append(LOGIN_USER_INFO);

    isNeedSaveUserInfo = true;
    FileUtils::getInstance()->isFileExist(writablePath, [=](bool isExist) {

        if (isExist) {
          ValueMap userInfo = FileUtils::getInstance()->getValueMapFromFile(writablePath);
          loginUserInfo.roomId = userInfo["roomId"].asString()    ;
          loginUserInfo.signature  = userInfo["signature"].asString() ;
          loginUserInfo.avatar  = userInfo["avatar"].asString() ;
          loginUserInfo.gender  = userInfo["gender"].asString() ;
          loginUserInfo.roomId  = userInfo["role"].asString()   ;
          loginUserInfo.signature  = userInfo["signature"].asString() ;
          loginUserInfo.nickname  = userInfo["nickname"].asString()  ;
          saveConnectMadId = userInfo["connect_macid"].asString();

          if(loginUserInfo.avatar.length() > 5){
              if(saveConnectMadId.length() > 0) {
                  isNeedSaveUserInfo = false;
              }
              downloadFriend(loginUserInfo.avatar, "登录用户头像");
          }else{
              initSocketIO();
          }
        } else {
          initSocketIO();
        }
    });
}

void HelloWorld::SioStatInfo(SIOClient *client, const std::string&data) {
    //BlueToothHelper::notifyTarget->setNotifyLabel("SioStatInfo");
}
void HelloWorld::SioStoreRoomid(SIOClient *client, const std::string &md5)
{
    if(md5.length()<3){
        return;
    }

    std::string jmd5 = md5.substr(1,md5.length()-2);
    std::string actName = "share-code-login";
    //std::string actName = "share-code";

    SocketIOHelper::getInstant()->emit(actName, jmd5);
}
void HelloWorld::SioShareCode(SIOClient *client, const std::string& url) {
    if(oneUserNode->getChildByName("running_baby") != nullptr) {
        this->scheduleOnce([=](float dt) {
            std::string jUrl = url.substr(1, url.length() - 2);
            downloadFriend(jUrl, "分享二维码");
        }, 0.0f, "分享二维码");
    }
}
void HelloWorld::SioOffline(SIOClient *client, const std::string&data) {

}
void HelloWorld::SioTalking(SIOClient *client,const std::string &data) {
    BlueToothHelper::notifyTarget->setNotifyLabel("SioStatInfo");
}
void HelloWorld::SioRoomCommentator(SIOClient *client, const std::string&data) {

}
void HelloWorld::SioOnConnect(SIOClient* client) {

}
void HelloWorld::SioOnMessage(SIOClient* client, const std::string& data) {

}
void HelloWorld::SioOnError(cocos2d::network::SIOClient* client, const std::string&data ) {
    initSocketIO(true);
}

void HelloWorld::SioOnClose(cocos2d::network::SIOClient* client) {
    initSocketIO(true);
}
void HelloWorld::SioRoomVisitors(SIOClient *client, const std::string& data) {

}

//下载之友
void HelloWorld::downloadFriend(std::string url,std::string id)
{
    //创建Request对象
    auto request = new HttpRequest();
    request->setUserData((void *)new std::string(id));
    //设置请求网址
    request->setUrl(url);
    //设置请求类型
    request->setRequestType(HttpRequest::Type::GET);
    //设置请求的数据
    //char data[50] = "data";
    //request->setRequestData(data,strlen(data));
    //完整的Request对象已经创建成功了

    request->setResponseCallback(CC_CALLBACK_2(HelloWorld::onHttpRequestCompleted, this));
    //创建HttpClient对象
    auto client = HttpClient::getInstance();//getInstance静态成员函数-单例模式模型
    client->setTimeoutForConnect(10);//当客户端向服务端发送请求超过这个时间，就会返回一个错误信息
    client->setTimeoutForRead(10);//接收数据的读取时间
    client->send(request);
    request->release();//释放请求
}

void HelloWorld::onHttpRequestCompleted(HttpClient *sender, HttpResponse *response)
{
    if (!response)
    {
        return;
    }

    HttpRequest* hRequest = response->getHttpRequest();
    std::string *id = static_cast<std::string*>(hRequest->getUserData());

    int statusCode = response->getResponseCode();
    if (statusCode != 200 ||
        !response->isSucceed()
            ){
        downFailed((*id), hRequest->getUrl());

        delete id;
        return;
    }


    downSuccess((*id), hRequest->getUrl(), (*response->getResponseData()));
    delete id;
}
//下载失败の回调
void HelloWorld::downFailed(const std::string id,const std::string url){

    //static_cast<Label *>(oneUserNode->getChildByName("running_title"))->setString(StringUtils::format("×任务：%s 错误:%s",id.c_str(),url.c_str()));
    downloadFriend(url, id);
}
//下载成功の回调
void HelloWorld::downSuccess(const std::string &id,const  std::string &url, std::vector<char> &cnt)
{
    // create texture from data
    Vec2 rsPos;
    if(runningSprite != nullptr){
        rsPos = runningSprite->getPosition();
    }else{
        rsPos = oneUserNode->getChildByName("show_rccode")->getChildByName("show_rccode_pic")->getPosition();
    }

    Texture2D* texture = nullptr;
    do
    {
        Image img;
        if (false == img.initWithImageData((const unsigned char *)cnt.data(), cnt.size()))
        {
            break;
        }

        texture = new Texture2D();
        if (false == texture->initWithImage(&img))
        {
            break;
        }

        if(static_cast<Label *>(oneUserNode->getChildByName("show_rccode"))!= nullptr){
            //oneUserNode->getChildByName("show_rccode")->setVisible(false);
            static_cast<Label *>(oneUserNode->getChildByName("show_rccode"))->removeFromParent();
        }

        //rsPos.y -= 30;
        auto reCodeS = Sprite::createWithTexture(texture);
        reCodeS->setAnchorPoint(Vec2(0.5, 1));//左下角
        reCodeS->setPosition(rsPos);
        reCodeS->setName("show_rccode_pic");

        //reCodeS->setName("show_rccode");
        reCodeS->setScale(runningBoundingBoxSize.size.width/reCodeS->getContentSize().width);

        auto mask = Sprite::create("sharecode_mask.png");
        mask->setAnchorPoint(Vec2(0.5, 1));
        mask->setPosition(rsPos);
        mask->setName("mask");
        mask->setScale(runningBoundingBoxSize.size.width/mask->getContentSize().width);


        auto clipNode = ClippingNode::create();
        clipNode->setAlphaThreshold(0.0f);
        clipNode->setName("show_rccode");
        clipNode->setStencil(mask);
        clipNode->addChild(reCodeS);
        clipNode->setAnchorPoint(Vec2(0, 0));
        clipNode->setOpacity(0);
        clipNode->runAction(FadeIn::create(1.0f));

        oneUserNode->addChild(clipNode);


        if(id == "分享二维码"){
            if(runningSprite != nullptr) {
                beforeDestoryRunning();

                this->scheduleOnce([&](float dt) {
                }, 0, "runningOut");
            }
        }

        if(id == "登录用户头像"){
            if(runningSprite != nullptr) {
                runningSprite->setVisible(false);
            }

            Vec2 pos = rsPos;
            pos.x += reCodeS->getBoundingBox().size.width*0.5;
            pos.y -= reCodeS->getBoundingBox().size.height;


            this->scheduleOnce([=](float dt) {
                if(HelloWorld::bleTabView == NULL){
                    return;
                }
                HelloWorld::bleTabView->setVisible(true);

                auto wxiconlogin = Sprite::create("wxiconlogin.png",Rect(0,41,39,39));//叹号：Rect(0,0,38,38)，对号：Rect(0,41,39,39)
                wxiconlogin->setName("wxlogin_icon");
                wxiconlogin->setAnchorPoint(Vec2(1, 0));//左下角
                wxiconlogin->setPosition(pos+Vec2(-2,2));
                //wxiconlogin->setVisible(false);
                oneUserNode->addChild(wxiconlogin);

            }, 1.5f, "wxlogin_icon_fade");

            //========================
            std::string writablePath = FileUtils::getInstance()->getWritablePath();
            std::string userIconPath = writablePath+loginUserInfo.signature+".png";
            Data writeData;
            writeData.copy((const unsigned char *)cnt.data(), cnt.size());
            FileUtils::getInstance()->writeDataToFile(writeData, userIconPath, [=](bool success) {
                if (success)
                {

                }
                else
                {

                }
            });
        }
    } while (0);

    CC_SAFE_RELEASE(texture);
}
void HelloWorld::initPromptLayer(){
    auto visibleSize = Director::getInstance()->getVisibleSize();

    auto promptLayer = LayerColor::create(Color4B(29, 29, 29, 125), visibleSize.width, visibleSize.height);
    promptLayer->setAnchorPoint(Vec2(0,1));
    promptLayer->setPosition(Vec2(visibleSize.width, 0));//));//visibleSize.width*0.70
    promptLayer->setName("promptLayer");

    auto bleLabel = Label::createWithTTF("连接向导:", "fonts/content.ttf", 32);
    bleLabel->setName("bleLabel");
    //bleLabel->setAnchorPoint(Vec2(0,1));
    bleLabel->setPosition(Vec2(10, 150));//, 0
    //bleLabel->getContentSize();getContentSize().height

    //promptLayer->addChild(bleLabel);

    connectBleLabel = Label::createWithTTF("\n\n\n连接初始化", "fonts/content.ttf", 24);
    connectBleLabel->setAnchorPoint(Vec2(0,0));
    //connectBleLabel->setHeight(connectBleLabel->getContentSize().height);
    float disLabX = visibleSize.width*0.30/2;
    float disLabY = visibleSize.height - connectBleLabel->getContentSize().height;
    connectBleLabel->setPosition(Vec2(20, disLabY));//visibleSize.width*0.64, 0
    promptLayer->addChild(connectBleLabel,3);

    this->addChild(promptLayer);
    //auto moveTo = MoveTo::create(1, Vec2(visibleSize.width*0.7, 0));
    //promptLayer->runAction(moveTo);
}

void HelloWorld::checkoutGlobal()
{
    HelloWorld::bleTabView = nullptr;
    SocketIOHelper::delegate =  static_cast<SocketIOHelperDelegate *>(nullptr);
    BlueToothHelper::notifyTarget = static_cast<BlueToothHelperDelegate *>(nullptr);


    HttpClient::getInstance()->setClearRequestPredicate(nullptr);
    HttpClient::getInstance()->setClearResponsePredicate(nullptr);
    HttpClient::getInstance()->clearResponseAndRequestQueue();
}

void HelloWorld::onEnterTransitionDidFinish()
{

    bool isFTM = JniHelper::callStaticBooleanMethod("org.cocos2dx.cpp.AppActivity", "isFromTongMeng");
    if(isFTM){
        BlueToothHelper::connectDeviceType = 3;
        auto scene = ClassPathChoose::createScene();
        Director::getInstance()->replaceScene(scene);

        BlueToothHelper::connectBleMacId;//JniHelper::callStaticBooleanMethod("org.cocos2dx.cpp.AppActivity", "getGoodCopyDataToken");
        return;
    }

    initGlobal();

    initBg();
    initPromptLayer();

    if(HelloWorld::currBleStatus == HelloWorld::BLE_STATUE_CONNECTED) {
        HelloWorld::currBleStatus = HelloWorld::BLE_STATUE_STOP;
        BlueToothHelper::disconnectBle();
    }

    auto visibleSize = Director::getInstance()->getVisibleSize();
    Vec2 origin = Director::getInstance()->getVisibleOrigin();

    /////////////////////////////
    // 2. add a menu item with "X" image, which is clicked to quit the program
    //    you may modify it.

    // add a "close" icon to exit the progress. it's an autorelease object
    auto closeItem = MenuItemImage::create(
            "CloseNormal.png",
            "CloseSelected.png",
            CC_CALLBACK_1(HelloWorld::menuCloseCallback, this));

    if (closeItem == nullptr ||
        closeItem->getContentSize().width <= 0 ||
        closeItem->getContentSize().height <= 0)
    {

    }
    else
    {
        float x = origin.x + visibleSize.width - closeItem->getContentSize().width/2;
        float y = origin.y + closeItem->getContentSize().height/2;
        closeItem->setPosition(Vec2(x,y));
    }

    // create menu, it's an autorelease object
    auto menu = Menu::create(closeItem, NULL);
    menu->setPosition(Vec2::ZERO);
    this->addChild(menu);

    /////////////////////////////
    // 3. add your codes below...
    //                              连接慧版
    auto item4 = MenuItemFont::create("", [&](Ref *sender) {
    });

    item4->setFontSizeObj(64);
    item4->setFontName("fonts/content.ttf");
    item4->setName("bandTitle");

    float menuTx = origin.x + visibleSize.width/2;// - closeItem->getContentSize().width/2;
    float menuTyA = origin.y + visibleSize.height/2;//-(item4->getContentSize().height/2);
    float menuTyB = origin.y + visibleSize.height-(item4->getContentSize().height/2);

    /* 移动到显示标签中*/
    //                                initinal
    displayLabel = Label::createWithTTF("", "fonts/content.ttf", 32);
    auto pMenu = MenuItemLabel::create(displayLabel, [&](Ref *sender) {});
    pMenu->setAnchorPoint(Vec2(0,1));
    pMenu->setPosition(Vec2(5,0));

    // add the label as a child to this layer
    this->addChild(displayLabel, 2);
    auto menuTop = Menu::create(item4, pMenu,  nullptr);
    menuTop->alignItemsHorizontally();
    menuTop->setPosition(Vec2(menuTx,menuTyA));
    menuTop->setName("menuTop");
    this->addChild(menuTop);

    menuTop->runAction(
            EaseIn::create(MoveTo::create(0.7, Vec2(menuTx,menuTyB)), 1)
    );

    blueToothY = origin.y + visibleSize.height - menuTop->getContentSize().height - 18;//

    searchBLEDeivce.clear();
    initBlueList();

    this->scheduleOnce([&](float dt) {
        if(searchBLEDeivce.size() > 0) {
            HelloWorld::bleTabView->reloadData();
        }
        beginScanBLE();

    },1.0f ,"beginScanBLE");


};
void HelloWorld::initSocketIO(bool isForceConn){
    float delta = 1.0f+CCRANDOM_0_1();
    this->scheduleOnce([=](float dt) {
        SocketIOHelper::checkConnection(isForceConn);
    },delta ,"initSocketIO");
};
void HelloWorld::initDrawTest() {
    auto s = Director::getInstance()->getWinSize();

    auto draw = DrawNode::create();
    addChild(draw, 10);

    draw->setLineWidth(4);
    draw->drawQuadBezier(Vec2(793.1428, 463.99), Vec2(1059.56, 393.727), Vec2(139.519,50.3), 3, Color4F::WHITE);

    return;
    draw->drawLine(Vec2(0,0), Vec2(500, 500), Color4F(1.0, 0.0, 0.0, 0.5));

    draw->setLineWidth(2);

    Vec2 origin = Director::getInstance()->getVisibleOrigin();
    draw->drawLine(Vec2(origin.x,origin.y), Vec2(200, 300), Color4F(0.0, 1.0, 0.0, 1.0));

    draw->setLineWidth(20);

    draw->drawQuadBezier(Vec2(origin.x,origin.y), Vec2(200, 300), Vec2(500, 500), 20, Color4F(0.0, 1.0, 1.0, 1.0));
}

void HelloWorld::initBg() {
    SimpleAudioEngine::getInstance()->pauseBackgroundMusic();
    SimpleAudioEngine::getInstance()->playBackgroundMusic("theme.mp3", true);
    SimpleAudioEngine::getInstance()->resumeBackgroundMusic();
    SimpleAudioEngine::getInstance()->setBackgroundMusicVolume(1.0f);


    auto visibleSize = Director::getInstance()->getVisibleSize();
    Vec2 origin = Director::getInstance()->getVisibleOrigin();

    //贴图的纹理图片宽高必须是2的n次幂，128x128
    auto bg = Sprite::create("background1.png");//, Rect(0, 0, visibleSize.width, visibleSize.height));
    Size mysize = bg->getContentSize();
    bg->setScaleX(visibleSize.width/mysize.width);
    bg->setScaleY(visibleSize.height/mysize.height);

    //贴图的纹理参数，水平重复平铺，垂直重复平铺
    /*
    Texture2D::TexParams tp = {                backend::SamplerFilter::LINEAR,
                                               backend::SamplerFilter::LINEAR,
                                               backend::SamplerAddressMode::REPEAT,
                                               backend::SamplerAddressMode::REPEAT
    };

    //bg->getTexture()->setTexParameters(tp);
     */
    bg->setAnchorPoint(Vec2::ZERO);
    bg->setPosition(0,0);//origin + Vec2(visibleSize.width/2, visibleSize.height/2));
    this->addChild(bg, -1);

    //================================
    auto wxscan = Sprite::create("wxscan.png");
    wxscan->setAnchorPoint(Vec2(0.5, 1));//左下角
    wxscan->setPosition(Vec2(visibleSize.width/2,visibleSize.height*0.92));
    wxscan->setScale((visibleSize.width*0.33)/wxscan->getContentSize().width);
    this->addChild(wxscan);

    //------------------------------  wxscan_board.png
    oneUserNode = Node::create();//LayerColor::create(Color4B(125,0,0,125), 100, 100);//Node::create();
    oneUserNode->setName("wxscan_node");
    oneUserNode->setAnchorPoint(Vec2(0.5, 1));//左下角
    oneUserNode->setPosition(Vec2(visibleSize.width/2,visibleSize.height*0.71));
    this->addChild(oneUserNode);

    auto wxscanB = Sprite::create("wxscan_board.png");
    wxscanB->setAnchorPoint(Vec2(0.5, 1));//左下角
    wxscanB->setScale((visibleSize.width*0.33)/wxscanB->getContentSize().width);
    wxscanB->setPosition(Vec2(0,0));
    oneUserNode->addChild(wxscanB);

    //=================================
    auto promptRedOKAni = Animation::create();
    for(int i=0;i<7;i++) {
        std::string filen = StringUtils::format("running/%d.png",i);
        promptRedOKAni->addSpriteFrameWithFile(filen);
    }
    promptRedOKAni->setDelayPerUnit(0.10f);
    promptRedOKAni->setRestoreOriginalFrame(true);

    runningSprite = Sprite::create("running.png");
    runningSprite->setName("running_baby");
    runningSprite->setAnchorPoint(Vec2(0.5, 1));//左下角
    runningSprite->setPosition(Vec2(0, -wxscanB->getBoundingBox().size.height*0.40));
    runningSprite->setScale((wxscanB->getBoundingBox().size.width*0.35)/runningSprite->getContentSize().width);
    runningSprite->runAction(RepeatForever::create(Animate::create(promptRedOKAni)));
    oneUserNode->addChild(runningSprite);

    runningBoundingBoxSize = runningSprite->getBoundingBox();

}

void HelloWorld::initLoginUserIcon()
{
    //----------------------------
    auto visibleSize = Director::getInstance()->getVisibleSize();

    auto clipNode = ClippingNode::create();
    auto mask = Sprite::create("avator_mask.png");
    mask->setAnchorPoint(Vec2(1, 1));

    clipNode->setAlphaThreshold(0.0f);
    clipNode->setStencil(mask);
    auto img = Sprite::create("user_avator.jpg");
//将头像大小缩放为模板大小
    img->setScale(mask->getContentSize().width/img->getContentSize().width);
    img->setAnchorPoint(Vec2(1, 1));
    clipNode->addChild(img);
    clipNode->setAnchorPoint(Vec2(1, 1));
    clipNode->setPosition(Vec2(visibleSize.width, visibleSize.height));
    this->addChild(clipNode);

    auto circle = Sprite::create("avator_mask_frame.png");
    circle->setAnchorPoint(Vec2(1, 1));
    circle->setPosition(Vec2(visibleSize.width, visibleSize.height));
    this->addChild(circle);
}

void HelloWorld::beforeDestoryRunning()
{
    auto visibleSize = Director::getInstance()->getVisibleSize();

    //static_cast<Label *>(oneUserNode->getChildByName("running_title"))->setString("");
    Vec2 rsPos = runningSprite->getPosition();
    Vec2 outScreen = Vec2(-visibleSize.width, rsPos.y);
    runningSprite->runAction(Sequence::create(Spawn::create(MoveTo::create(2, outScreen),
                                                            ScaleTo::create(2, 0.2),
                                                            FadeOut::create(2.0f),
                                                            nullptr
                                              ),
                                              CallFuncN::create(CC_CALLBACK_0(HelloWorld::destoryRunning,this)),
                                              nullptr
                             )
    );
}

void HelloWorld::destoryRunning()
{
    runningSprite = nullptr;
}

void HelloWorld::initKeyBoard(){
    auto listener = EventListenerKeyboard::create();
    listener->onKeyPressed = [=](EventKeyboard::KeyCode keyCode, Event* event){
        ControlCode pressKey = ControlCode(keyCode);
        HelloWorld::setKeyAct(pressKey);
//        auto promptxx = StringUtils::format("按下键盘：%d", static_cast<int>(keyCode));
//        BlueToothHelper::notifyTarget->setNotifyLabel(promptxx);
    };

    listener->onKeyReleased = [=](EventKeyboard::KeyCode keyCode, Event* event){
//        auto promptxx = StringUtils::format("抬起键盘：%d", static_cast<int>(keyCode));
//        BlueToothHelper::notifyTarget->setNotifyLabel(promptxx);
    };

    _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
}

void HelloWorld::setKeyAct(ControlCode &pressKey)
{
    //auto prmpptStr = StringUtils::format("KC=%d",pressKey);
    //BlueToothHelper::notifyTarget->setNotifyLabel(prmpptStr);

    //如果按返回就退出
    if(pressKey == KEY_RETURN ||
       pressKey == KEY_TV_RETURN
    ){
        BlueToothHelper::notifyTarget->setNotifyLabel("ヾ(￣▽￣)Bye~Bye~");
        Director::getInstance()->end();
    }

    if(pressKey == KEY_DOWN &&
       HelloWorld::currBleStatus != HelloWorld::BLE_STATUE_CONNECTED
    ){
        HelloWorld::resetOneBle(curBleCellIdx);

        curBleCellIdx++;

        if(curBleCellIdx>=searchBLEDeivce.size()){
            curBleCellIdx--;
        }
    }

    if(pressKey == KEY_UP &&
       HelloWorld::currBleStatus != HelloWorld::BLE_STATUE_CONNECTED
            ){
        HelloWorld::resetOneBle(curBleCellIdx);

        curBleCellIdx--;

        if(curBleCellIdx<0){
            curBleCellIdx = 0;
        }
    }

    if(pressKey == KEY_CHOOSE){
        if(curBleCellIdx >= 0) {
            connectBleList(curBleCellIdx);
        }
    }

    if(pressKey == KEY_DOWN ||
       pressKey == KEY_UP
            ) {
        if(HelloWorld::currBleStatus != HelloWorld::BLE_STATUE_CONNECTED) {
            chooseBleList(curBleCellIdx);
        }
    }

}

void HelloWorld::resetOneBle(int resetBleCellIdx) {
    if(resetBleCellIdx < 0 ||resetBleCellIdx>searchBLEDeivce.size()){ return;}

    TableViewCell *oneCell = bleTabView->cellAtIndex(curBleCellIdx);
    if(oneCell == nullptr){
        return;
    }
    auto oneLab = (Label*)oneCell->getChildByName("nameAndMac");
    if(oneLab == nullptr){
        return;
    }
    oneLab->disableEffect();
}

void HelloWorld::connectBleList(int curBleCellIdx){

    for(int i=0;i<searchBLEDeivce.size();i++){
        TableViewCell *oneCell = bleTabView->cellAtIndex(curBleCellIdx);
        if(oneCell == nullptr){
            return;
        }
        auto oneLab = (Label*)oneCell->getChildByName("nameAndMac");

        auto oneSprite = (Sprite*)oneCell->getChildByName("logo");
        auto pRotate = RotateBy::create(0, 0);
        oneSprite->runAction(pRotate);
    }

    //curBleCellIdx
    TableViewCell *oneCell = bleTabView->cellAtIndex(curBleCellIdx);

    if(oneCell) {
        HelloWorld::isDisplayDetail = true;

        auto oneLab = (Label*)oneCell->getChildByName("nameAndMac");
        oneLab->enableOutline(Color4B(0,0, 255, 255),2);

        auto oneSprite = (Sprite*)oneCell->getChildByName("logo");
        auto pRotate = RotateBy::create(0.5, 360);
        auto pRepeatRotate = RepeatForever::create(pRotate);
        oneSprite->runAction(pRepeatRotate);

        auto visibleSize = Director::getInstance()->getVisibleSize();

        auto promptLayer = (LayerColor*)(static_cast<HelloWorld*>(BlueToothHelper::notifyTarget)->getChildByName("promptLayer"));
        auto moveTo = MoveTo::create(1, Vec2(visibleSize.width*0.7, 0));
        //promptLayer->runAction(moveTo);
    }

    auto oneBleDecive = searchBLEDeivce.begin();
    for(int i=0;i<curBleCellIdx;i++){oneBleDecive++;}

    HelloWorld::currBleStatus = HelloWorld::BLE_STATUE_CONNECTING;

    BlueToothHelper::ConnectByMacId(oneBleDecive->first);
    std::string pp = "开始连接:"+oneBleDecive->second;
    BlueToothHelper::connectBleMacId = oneBleDecive->first;
    if(BlueToothHelper::notifyTarget != nullptr) {
        BlueToothHelper::notifyTarget->setNotifyLabel(pp);
    }

}


void HelloWorld::chooseBleList(int curBleCellIdx){
    BlueToothHelper::notifyTarget->setNotifyLabel("按‘确认’开始连接...");
    for(int i=0;i<searchBLEDeivce.size();i++){
        TableViewCell *oneCell = bleTabView->cellAtIndex(curBleCellIdx);
        if(oneCell == nullptr){
            return;
        }
        auto oneLab = (Label*)oneCell->getChildByName("nameAndMac");

        auto oneSprite = (Sprite*)oneCell->getChildByName("logo");
        auto pRotate = RotateBy::create(0, 0);
        //auto pRepeatRotate = RepeatForever::create(pRotate);
        oneSprite->runAction(pRotate);
    }

    //curBleCellIdx
    TableViewCell *oneCell = bleTabView->cellAtIndex(curBleCellIdx);

    if(oneCell) {
        auto oneLab = (Label*)oneCell->getChildByName("nameAndMac");
        oneLab->enableOutline(Color4B(0,   0, 255, 125),1);
    }
}

//放下一个命令
void HelloWorld::setOneAct(ActCmd &oneCmd)
{
    if(oneCmd.act == Pen_Write){
        std::string cmd = "得到一个写命令,";

        if(oneCmd.actDetail == PenStatus_Down){
            cmd.append(",按下,x=");
        }

        if(oneCmd.actDetail == PenStatus_Up){
            cmd.append(",抬起,x=");
        }

        if(oneCmd.actDetail == PenStatus_Leave){
            cmd.append(",离开,x=");
        }

        if(oneCmd.actDetail == PenStatus_Hover){
            cmd.append(",悬浮,x=");
        }

        cmd.append(std::to_string(oneCmd.x)).append(",y=").append(std::to_string(oneCmd.y)).append(",presure=").append(std::to_string(oneCmd.presure));

        //putNotifyLabel(cmd);
    }

    if(oneCmd.act == Pen_Ctl){
        std::string cmd = "得到一个控制命令-";
        if(oneCmd.actDetail == PenStatus_SAVE){
            cmd.append("保存");
        }
        if(oneCmd.actDetail == PenStatus_CLEAR){
            cmd.append("清除");
        }
        if(oneCmd.actDetail == PenStatus_BLUE){
            cmd.append("蓝");
        }
        if(oneCmd.actDetail == PenStatus_BLACK){
            cmd.append("黑");
        }
        if(oneCmd.actDetail == PenStatus_RED){
            cmd.append("红");
        }
        if(oneCmd.actDetail == PenStatus_PEN_FINE){
            cmd.append("细笔");
        }
        if(oneCmd.actDetail == PenStatus_PEN_MEDIUM){
            cmd.append("中笔");
        }
        if(oneCmd.actDetail == PenStatus_PEN_BOLD){
            cmd.append("粗笔");
        }
        if(oneCmd.actDetail == PenStatus_MOUSE_CHOOSE){
            cmd.append("选鼠");
        }
        if(oneCmd.actDetail == PenStatus_PEN_CHOOSE){
            cmd.append("选笔");
        }
        if(oneCmd.actDetail == PenStatus_NEXT){
            cmd.append("下一页");
        }
        if(oneCmd.actDetail == PenStatus_PREV){
            cmd.append("上一页");
        }

        //putNotifyLabel(cmd);
    }

}

void HelloWorld::beginScanBLE()
{
#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
    //1. 获取activity静态对象
    JniMethodInfo minfo;
    bool isHave = JniHelper::getStaticMethodInfo(minfo,
                                                 "org.cocos2dx.cpp.AppActivity",
                                                 "getMe",
                                                 "()Lorg/cocos2dx/cpp/AppActivity;");
    jobject activityObj;
    if (isHave)
    {
        //调用静态函数getJavaActivity，获取java类对象。
        activityObj = minfo.env->CallStaticObjectMethod(minfo.classID, minfo.methodID);
        LOGD("jni: calling org/cocos2dx/cpp/AppActivity/getMe()");

    }else{
        LOGD("jni: org.cocos2dx.cpp.AppActivity.getMe 不存在");

    }

    //2. 查找displayWebView接口，获取其函数信息，并用jobj调用
    isHave = JniHelper::getMethodInfo(minfo,"org.cocos2dx.cpp.AppActivity","scanLeDevice", "(Z)V");

    if (!isHave)
    {
        LOGD("jni: scanLeDevice 函数不存在");
    }
    else
    {
        jboolean isScan = JNI_TRUE;

        //调用displayWebView函数，并传入参数
        minfo.env->CallVoidMethod(activityObj, minfo.methodID, isScan);
        LOGD("开始扫描");
    }
#endif
}

void HelloWorld::menuCloseCallback(Ref* pSender)
{
    //Close the cocos2d-x game scene and quit the application
    Director::getInstance()->end();

    /*To navigate back to native iOS screen(if present) without quitting the application  ,do not use Director::getInstance()->end() as given above,instead trigger a custom event created in RootViewController.mm as below*/

    //EventCustom customEndEvent("game_scene_close_event");
    //_eventDispatcher->dispatchEvent(&customEndEvent);
}


void HelloWorld::tableCellTouched(TableView* table, TableViewCell* cell)
{
    CCLOG("cell touched at index: %ld", static_cast<long>(cell->getIdx()));
    curBleCellIdx = cell->getIdx();
    connectBleList(cell->getIdx());
}

void HelloWorld::initBlueList()
{
    Size winSize =  Director::getInstance()->getVisibleSize();
    Vec2 origin = Director::getInstance()->getVisibleOrigin();

    float tabPosX = origin.x + winSize.width*0.7;
    float tabPosY = origin.y + winSize.height*0.1;

    float tabWidth = winSize.width*0.64;
    float tabHeight= winSize.height*0.7;

    HelloWorld::bleTabView = TableView::create(this, Size(tabWidth, tabHeight));
    HelloWorld::bleTabView->setDirection(ScrollView::Direction::VERTICAL);
    HelloWorld::bleTabView->setPosition(Vec2(tabPosX,tabPosY));
    HelloWorld::bleTabView->setDelegate(this);
    HelloWorld::bleTabView->setVerticalFillOrder(TableView::VerticalFillOrder::TOP_DOWN);
    this->addChild(HelloWorld::bleTabView);

    //HelloWorld::bleTabView->setVisible(false);
}


Size HelloWorld::tableCellSizeForIndex(TableView *table, ssize_t idx)
{
    /*
    if (idx == 2) {
        return Size(100, 100);
    }*/
    Size winSize = Director::getInstance()->getWinSize();

    float tabWidth = winSize.width*0.64;
    float tabHeight= winSize.height*0.1;//7/8;

    return Size(tabWidth, tabHeight);
}

TableViewCell* HelloWorld::tableCellAtIndex(TableView *table, ssize_t idx)
{
    auto oneBleDecive = searchBLEDeivce.begin();
    for(int i=0;i<idx;i++){oneBleDecive++;}
    auto xx = StringUtils::format("%s\t(%s)", oneBleDecive->second.c_str(),oneBleDecive->first.c_str());
    if(oneBleDecive->first == "00-00-00-00-00-00"){
        xx = oneBleDecive->second;
    }

    TableViewCell *cell = table->dequeueCell();
    if (!cell) {
        cell = new TableViewCell();
        //cell->autorelease();

        //前边的 logo
        //bluetoothlogo_btg.png bluetoothlogo_dc.png  bluetoothlogo_dz.png
        std::string fileName = "bluetoothlogo_btg.png";
        if(oneBleDecive->second.find_first_of("XJ") == 0){
            fileName = "bluetoothlogo_dc.png";
        }
        if(oneBleDecive->second.find_first_of("TD-") == 0){
            fileName = "bluetoothlogo_dz.png";
        }
        if(oneBleDecive->first == "00-00-00-00-00-00"){
            fileName = "bluetoothlogo_btg.png";
        }

        auto sprite = Sprite::create(fileName);
        //sprite->setAnchorPoint(Vec2::ZERO);
        sprite->setScale(0.5);
        sprite->setPosition(Vec2(0, sprite->getContentSize().height/3));
        sprite->setOpacity(125);
        sprite->setName("logo");
        cell->addChild(sprite);

        //蓝牙名称
        auto label = Label::createWithTTF(xx.c_str(), "fonts/content.ttf", 32);//Label::createWithSystemFont(string, "Helvetica", 10.0);
        label->setTextColor(Color4B::ORANGE);
        label->setAnchorPoint(Vec2::ZERO);
        label->setName("nameAndMac");
        label->setPosition(Vec2(sprite->getContentSize().width, 0));
        cell->addChild(label);
    }else{
        auto label = (Label*)cell->getChildByName("nameAndMac");
        label->setString(xx);
    }

    if(saveConnectMadId == oneBleDecive->first) {
        this->scheduleOnce([=](float dt) {
            curBleCellIdx = idx;
            connectBleList(idx);
        }, 0.5f, "joining_pad");
    }



    return cell;
}

ssize_t HelloWorld::numberOfCellsInTableView(TableView *table)
{
    return searchBLEDeivce.size();
}